const API = require('../../utils/api')
const app = getApp()
const { showToast } = require('../../utils/util')
// 引入SDK核心类，js文件根据自己业务，位置可自行放置
var QQMapWX = require('../../common/qqmap-wx-jssdk1.2/qqmap-wx-jssdk.min')
var qqmapsdk

Page({
    /**
     * 页面的初始数据
     */
    data: {
        inviterUserId: '',
        tagCurrent: 1,
        province: [['浙江省'], ['杭州市']],
        picker: {
            areaList: ['全部', '上城区', '下城区', '西湖区', '江干区', '拱墅区', '滨江区', '萧山区', '余杭区', '临安区', '富阳区', '建德', '桐庐县', '淳安县'],
        },
        areaList: ['全部', '上城区', '下城区', '西湖区', '江干区', '拱墅区', '滨江区', '萧山区', '余杭区', '临安区', '富阳区', '建德', '桐庐县', '淳安县'],
        volumeList: ['全部', '0-100', '100-200', '200-300', '300-500', '500-1000', '1000-5000'],
        screenList: [
            {
                title: '城市',
                children: ['全部', '杭州'],
                current: 0,
            },
            {
                title: '位置',
                children: ['全部', '上城区', '下城区', '西湖区', '江干区', '拱墅区', '滨江区', '萧山区', '余杭区', '临安区', '富阳区', '建德', '桐庐县', '淳安县'],
                current: 0,
            },
            {
                title: '面积',
                children: ['全部', '0-100', '100-200', '200-300', '300-500', '500-1000', '1000-5000'],
                current: 0,
            }
        ],
        screenList_company: [
            {
                title: '城市',
                children: ['全部', '杭州'],
                current: 0,
            },
            {
                title: '地区',
                children: ['全部', '上城区', '下城区', '西湖区', '江干区', '拱墅区', '滨江区', '萧山区', '余杭区', '临安区', '富阳区', '建德', '桐庐县', '淳安县'],
                current: 0,
            },
            {
                title: '行业',
                children: ['全部', '农、林、牧、渔业', '采矿业', '制造业', '电力、燃气及水的生产和供应业', '建筑业', '交通运输、仓储和邮政业', '信息传输、计算机服务和软件业', '批发和零售业', '住宿和餐饮业', '金融业', '房地产业', '租赁和商务服务业', '科学研究、技术服务和地质勘查业', '水利、环境和公共设施管理业', '居民服务和其他服务业'],
                current: 0,
            },
            {
                title: '认证状态',
                children: ['全部', '待认证', '待审核', '已认证'],
                current: 0,
            },
        ],
        parkQuery: {
            acreage: '', //房源范围
            //acreage:'', //面积
            //price:'', //价格
            area: '', //区域
            city: '', //城市
            parkType: '',//投放类型
            pageSize: 10,
            pageNum: 1,
        },
        parkList: [],
        reachBottomShow: false,
        formData: {
            search: '', // 关键字
            classify: '10', // 10 园区分类 20 企业分类 30 房源分类
            acreage: '', // 面积
            area: '', // 区域
            city: '杭州', // 城市
            companyOrder: '', // 企业1升序2降序
            housingOrder: '', // 房源1升序2降序
            parkType: '写字楼', // 园区类型
            pageSize: 10,
            pageNum: 1,
        },
        companyQuery: {
            approveType: '', //认证状态
            industry: '', //行业
            area: '', //区域
            city: '', //城市
            pageSize: 10,
            pageNum: 1,
        },
        companyList: [],
        //canvas
        canvasShow: false,
        // 园区 企业 房源 数量
        countPark: {
            companyCount: 0,
            companyNewToday: '',
            housingCount: 0,
            housingNewToday: '',
            parkCount: 0,
            parkNewToday: '',
        },
        // 房源商品分享对象
        shareContent: null
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        //2. 获取启动参数 二维码
        if (options && options.scene) {
            //重置登陆状态
            app.globalData.userInfo = {}
            app.globalData.hasUserInfo = false

            let query = {}
            let scene = decodeURIComponent(options.scene).split('&')
            scene.forEach(ele => {
                let key = ele.split('=')[0]
                query[key] = ele.split('=')[1]
            })
            // console.log('格式化启动参数', query)
            let globalQuery = {
                userId: query.uid,
                spreadType: query.st,
                type: query.t,
            }
            query.yqid ? globalQuery.gardenId = query.yqid : ''
            query.qyid ? globalQuery.enterpriseId = query.qyid : ''
            app.globalData.inviterUserId = query.uid
            app.globalData.qrQuery = globalQuery
        }

        // 实例化API核心类
        qqmapsdk = new QQMapWX({
            key: 'DXTBZ-YDREU-SD7VG-BRWIV-ELVTV-OHF4Z'
        });

        let that = this
        // app.login(userData)
        // function userData(data) {
        //     that.setData({
        //         userInfo: data,
        //         inviterUserId: app.globalData.inviterUserId
        //     })
        // }
        that.baijiaxing()
        that.get_park_list()
        that.get_recommend_park_list()
        that.get_parkAndCompany_total()
        that.get_back_garden_house_area_list()
        this.getCountPark()
    },
    /**
     * 搜索input变化事件
     */
    searchChange(event) {
        this.data.formData.search = event.detail.value
    },
    /**
     * 搜索input 确认事件
     */
    searchConfirm() {
        this.data.formData.pageNum = 1
        this.data.formData.classify == 10 ? this.get_park_list() : this.data.formData.classify == 20 ? this.getCompanyList() : this.getAppletHomeHousing()
    },
    /**
     * 排序事件
     */
    sortEvent(event) {
        const { key, value } = event.currentTarget.dataset
        const formData = this.data.formData
        formData.companyOrder = ''
        formData.housingOrder = ''
        formData[key] = value
        this.setData({ formData })
        this.data.formData.pageNum = 1
        this.data.formData.classify == 10 ? this.get_park_list() : this.data.formData.classify == 20 ? this.getCompanyList() : this.getAppletHomeHousing()
    },
    /**
     * 写字楼 产业园 分类事件
     */
    parkClassifyEvent(event) {
        const { classify, parkType } = this.data.formData
        const value = event.currentTarget.dataset.value
        if (parkType == value) return
        this.data.formData.pageNum = 1
        this.setData({ 'formData.parkType': value })
        this.getCountPark()
        classify == 10 ? this.get_park_list() : classify == 20 ? this.getCompanyList() : this.getAppletHomeHousing()
    },
    /**
     * 园区 企业 房源 分类事件
     */
    classifyEvent(event) {
        const { key, value } = event.currentTarget.dataset
        if (this.data.formData.classify == value) return
        this.data.formData.pageNum = 1
        value == '10' ? this.get_park_list() : value == '20' ? this.getCompanyList() : this.getAppletHomeHousing()
        const formData = this.data.formData
        formData[key] = value
        this.setData({ formData })
    },
    /**
     * 园区 企业 房源 数量
     */
    async getCountPark() {
        const { city, parkType } = this.data.formData
        const res = await API.get_count_park({
            city: city,
            gardenType: parkType
        })
        this.setData({ countPark: res.data })
    },
    /**
     * 查询条件事件
     */
    querySelectEvent(event) {
        const list = this.data[event.currentTarget.dataset.arr]
        const value = list[event.detail - 0] == '全部' ? '' : list[event.detail - 0]
        this.setData({ [`formData.${event.currentTarget.dataset.key}`]: value })
        this.data.formData.pageNum = 1
        this.data.formData.classify == 10 ? this.get_park_list() : classify == 20 ? this.getCompanyList() : this.getAppletHomeHousing()
    },
    /**
         * 接口 - 园区列表
         */
    async get_park_list() {
        const res = await API.get_park_list(this.data.formData)
        if (res.code != 200) return showToast(res.msg)
        const parkList = this.data.formData.pageNum == 1 ? res.rows : this.data.parkList.concat(res.rows)
        this.setData({ parkList })
    },
    /**
     * 接口 - 企业列表
     */
    async getCompanyList() {
        const res = await API.get_company_list(this.data.formData)
        if (res.code != 200) return showToast(res.msg)
        res.rows.forEach(ele => {
            ele.establishTime ? ele.establishTime = ele.establishTime.split(' ')[0].replace(/-/g, '/') : ''
            ele.phone ? ele.phone = ele.phone.substring(0, 3) + '****' + ele.phone.substring(7, 11) : ''
        })
        const parkList = this.data.formData.pageNum == 1 ? res.rows : this.data.parkList.concat(res.rows)
        this.setData({ parkList })
    },

    /**
         * 接口 - 房源列表
         */
    async getAppletHomeHousing() {
        const userInfo = app.globalData.userInfo
        const res = await API.get_applet_home_housing(this.data.formData)
        if (res.code != 200) return showToast(res.msg)
        res.rows.forEach(item => item.companySign = userInfo.companySign)
        const parkList = this.data.formData.pageNum == 1 ? res.rows : this.data.parkList.concat(res.rows)
        this.setData({ parkList })
    },
    /**
     * 接口 - 企业列表
     */
    get_company_list: function () {
        let that = this
        // wx.showLoading({
        //   title: '加载中',
        // })
        API.get_company_list(that.data.companyQuery).then(res => {
            if (res.code == 200) {
                let companyList = res.rows.map(ele => {
                    ele.establishTime ? ele.establishTime = ele.establishTime.split(' ')[0].replace(/-/g, '/') : ''
                    ele.phone ? ele.phone = ele.phone.substring(0, 3) + '****' + ele.phone.substring(7, 11) : ''
                    return ele
                })
                that.setData({
                    companyList: [...that.data.companyList, ...companyList],
                })
                if (res.rows.length == 10) {
                    that.setData({
                        reachBottomShow: true
                    })
                } else {
                    that.setData({
                        reachBottomShow: false
                    })
                }
                setTimeout(() => {
                    wx.hideLoading()
                }, 1000);
            } else {
                wx.hideLoading()
                wx.showToast({
                    title: res.msg,
                    icon: 'none'
                })
            }
        })
    },

    /**
     * 接口 - 园区企业数量统计
     */
    get_parkAndCompany_total: function () {
        let that = this
        API.get_parkAndCompany_total().then(res => {
            that.setData({
                parkAndCompany_total: res.data
            })
        })
    },

    /**
     * 通知 - 百家姓
     */
    baijiaxing: function () {
        let arr = '赵|钱|孙|李|周|吴|郑|王|冯|陈|楮|卫|蒋|沈|韩|杨|朱|秦|尤|许|何|吕|施|张|孔|曹|严|华|金|魏|陶|姜|戚|谢|邹|喻|柏|水|窦|章|云|苏|潘|葛|奚|范|彭|郎|鲁|韦|昌|马|苗|凤|花|方|俞|任|袁|柳|酆|鲍|史|唐|费|廉|岑|薛|雷|贺|倪|汤|滕|殷|罗|毕|郝|邬|安|常|乐|于|时|傅|皮|卞|齐|康|伍|余|元|卜|顾|孟|平|黄|和|穆|萧|尹|姚|邵|湛|汪|祁|毛|禹|狄|米|贝|明|臧|计|伏|成|戴|谈|宋|茅|庞|熊|纪|舒|屈|项|祝|董|梁|杜|阮|蓝|闽|席|季|麻|强|贾|路|娄|危|江|童|颜|郭|梅|盛|林|刁|锺|徐|丘|骆|高|夏|蔡|田|樊|胡|凌|霍|虞|万|支|柯|昝|管|卢|莫|经|房|裘|缪|干|解|应|宗|丁|宣|贲|邓|郁|单|杭|洪|包|诸|左|石|崔|吉|钮|龚|程|嵇|邢|滑|裴|陆|荣|翁|荀|羊|於|惠|甄|麹|家|封|芮|羿|储|靳|汲|邴|糜|松|井|段|富|巫|乌|焦|巴|弓|牧|隗|山|谷|车|侯|宓|蓬|全|郗|班|仰|秋|仲|伊|宫|宁|仇|栾|暴|甘|斜|厉|戎|祖|武|符|刘|景|詹|束|龙|叶|幸|司|韶|郜|黎|蓟|薄|印|宿|白|怀|蒲|邰|从|鄂|索|咸|籍|赖|卓|蔺|屠|蒙|池|乔|阴|郁|胥|能|苍|双|闻|莘|党|翟|谭|贡|劳|逄|姬|申|扶|堵|冉|宰|郦|雍|郤|璩|桑|桂|濮|牛|寿|通|边|扈|燕|冀|郏|浦|尚|农|温|别|庄|晏|柴|瞿|阎|充|慕|连|茹|习|宦|艾|鱼|容|向|古|易|慎|戈|廖|庾|终|暨|居|衡|步|都|耿|满|弘|匡|国|文|寇|广|禄|阙|东|欧|殳|沃|利|蔚|越|夔|隆|师|巩|厍|聂|晁|勾|敖|融|冷|訾|辛|阚|那|简|饶|空|曾|毋|沙|乜|养|鞠|须|丰|巢|关|相|查|后|荆|红|游|竺|权|逑|盖|益|桓|公|司马'.split('|')

        let noticeArr = []
        let i = 0
        while (i < 10) {
            let item = {
                name: arr[Math.floor(Math.random(0, 4) * 400)],
                price: Math.floor(Math.random() * 20000)
            }
            item.price < 5000 ? item.price = 5000 : item.price
            noticeArr.push(item)
            i++
        }
        this.setData({
            noticeArr
        })
    },

    /**
     * 接口 - 园区推荐列表
     */
    get_recommend_park_list: function () {
        let that = this
        API.get_recommend_park_list().then(res => {
            if (res.code == 200) {
                let rows = res.rows.map(ele => {
                    let locationIndex = ele.location.indexOf('区')
                    if (locationIndex != -1) {
                        ele.location_text = ele.location.substring(0, locationIndex + 1)
                        ele.location.indexOf('市') != -1 ? ele.location_text = ele.location_text.replace('市', ' · ') : ''
                    } else {
                        ele.location_text = ele.location
                    }
                    return ele
                })
                that.setData({
                    recommendParkList: rows
                })
            }
        })
    },

    /**
    * 接口 - 房源面积
    */
    get_back_garden_house_area_list: function () {
        let that = this
        API.get_back_garden_house_area_list().then(res => {
            // console.log(res);
            let screenList = that.data.screenList
            let rows = res.rows
            rows.unshift({
                id: '',
                scope: '全部'
            })
            screenList[2] = {
                title: '面积',
                current: 0,
                children: rows
            }
            that.setData({
                screenList
            })
            // console.log(that.data.screenList)
        })
    },



    /**
     * 事件 - canvas分享 园区
     */
    sharePark: function (e) {
        if (!app.globalData.hasUserInfo) {
            wx.showToast({
                title: '您还没有登陆哦',
                icon: 'none'
            })

            setTimeout(() => {
                wx.reLaunch({
                    url: '/pages/login/login?back=/pages/park/park',
                })
            }, 1000)
            return
        }
        this.setData({
            shareData: e.currentTarget.dataset.item,
            page: 'pages/park/park',
            canvasId: 'shareImg' + Date.parse(new Date()),
            canvasShow: true,
        })
        // console.log('打开组件画图',e.currentTarget.dataset.item)
    },

    /**
     * 事件 - 园区筛选改变
     */
    screenChange: function (e) {
        let index = e.currentTarget.id
        let children = e.detail.value
        let value = this.data.screenList[index].children[children]
        children == 0 ? value = '' : ''
        let scope = this.data.screenList[index].children[children].scope
        scope == '全部' ? scope = '' : ''
        this.setData({
            ['screenList[' + index + '].current']: children,
            ['parkQuery.pageNum']: 1,
            parkList: [],
            reachBottomShow: true, //打开分页
        })
        if (index == 0) {
            // console.log('城市', children)
            this.setData({
                ['parkQuery.city']: value
            })
        } else if (index == 1) {
            // console.log('地区', children)
            this.setData({
                ['parkQuery.area']: value
            })
        } else if (index == 2) {
            // console.log('面积', children)
            this.setData({
                // ['parkQuery.acreage']: value
                ['parkQuery.acreage']: scope
            })
        } else if (index == 3) {
            // console.log('投放类型', children)
            this.setData({
                ['parkQuery.parkType']: value
            })
        }
        // }else if( index == 3 ){
        //     console.log('价格', children)
        //     this.setData({
        //         ['parkQuery.price']: value
        //     })
        // }
        // console.log('参数', value, this.data.parkQuery)
        this.get_park_list()
    },

    /**
     * 事件 - 企业筛选改变
     */
    companyScreenChange: function (e) {
        let index = e.currentTarget.id
        let children = e.detail.value
        let value = this.data.screenList_company[index].children[children]
        children == 0 ? value = '' : ''
        this.setData({
            ['screenList_company[' + index + '].current']: children,
            ['companyQuery.pageNum']: 1,
            companyList: [],
            reachBottomShow: true,
        })
        if (index == 0) {
            // console.log('城市', children)
            this.setData({
                ['companyQuery.city']: value
            })
        } else if (index == 1) {
            // console.log('地区', children)
            this.setData({
                ['companyQuery.area']: value
            })
        } else if (index == 2) {
            // console.log('行业', children)
            this.setData({
                ['companyQuery.industry']: value
            })
        } else if (index == 3) {
            // console.log('认证状态', children)
            if (children == 1) {
                value = 0
            } else if (children == 2) {
                value = 1
            } else if (children == 3) {
                value = 2
            }
            this.setData({
                ['companyQuery.approveType']: value
            })
        }
        // console.log('参数', value, this.data.companyQuery)
        this.get_company_list()
    },

    /**
     * 事件 - 地图导航
     */
    openLocation: function (e) {
        let that = this
        let location = e.currentTarget.dataset.location
        //调用地址解析接口
        qqmapsdk.geocoder({
            //获取表单传入地址
            address: location,
            success: function (res) {
                // console.log(res);
                var result = res.result;
                var latitude = result.location.lat; //维度
                var longitude = result.location.lng; //经度

                // that.getReverseGeocoder(latitude, longitude)

                wx.openLocation({
                    latitude,
                    longitude,
                    name: e.currentTarget.dataset.name,
                    address: location,
                    scale: 18
                })
            },
            fail: function (error) {
                console.error(error);
                wx.showToast({
                    title: '获取定位失败,请稍后重试',
                    icon: 'none'
                })
            },
        })
    },

    /**
     * 地图 - 获取坐标位置描述
     */
    getReverseGeocoder: function (latitude, longitude) {
        qqmapsdk.reverseGeocoder({
            location: {
                latitude: latitude,
                longitude: longitude
            },
            success: function (res) {
                // console.log( '获取坐标位置描述', res )
            }
        })
    },

    /**
     * 阻止轮播图手动切换
     */
    stopTouchMove() {
        return false
    },
    enterprise_authentication() {
        console.log('enterprise_authentication---------------------')
        // !app.globalData.hasUserInfo || !app.globalData.userInfo
        // console.log("app.globalData.userInf",app.globalData.hasUserInfo, app.globalData.userInfo)
        const url = '/pages/home/enterprise/enterprise'
        // if (app.globalData.userInfo.companySign == 0) url = '/pages/park/company/edit/edit'
        wx.navigateTo({ url })
    },
    /**
     * 统一路由
     */
    routeMemu: function (e) {
        let type = e.currentTarget.id
        let that = this
        const token = wx.getStorageSync('token')
        if (!token) {
            wx.showToast({
                title: '您还没有登录哦',
                icon: 'none'
            })

            setTimeout(() => {
                wx.navigateTo({
                    url: '/pages/login/login?back=/pages/home/home',
                })
            }, 1000)
        } else {
            routeList()
        }
        function routeList() {
            if (type == 1) {
                wx.navigateTo({
                    url: './join/join',
                })
            } else if (type == 2) {
                wx.navigateTo({
                    url: '/pages/park/company/edit/intro',
                })
            } else if (type == 3) {
                wx.navigateTo({
                    url: '/pages/home/marketing/marketing',
                })
            } else if (type == 4) {
                wx.navigateTo({
                    url: '/pages/index/set-case/set-case',
                })
            } else if (type == 5) {
                wx.navigateTo({
                    url: '/pages/home/service/list',
                })
            } else if (type == 6) {
                //登陆拦截
                if (!token) {
                    wx.showToast({
                        title: '您还没有登陆哦',
                        icon: 'none'
                    })

                    setTimeout(() => {
                        wx.reLaunch({
                            url: '/pages/login/login?back=/pages/home/home',
                        })
                    }, 1000)
                    return
                }
                //判断是否有园区
                if (app.globalData.userInfo.gardenSign == 0) {
                    wx.navigateTo({
                        url: '/pages/home/apply/apply',
                    })
                } else {
                    wx.navigateTo({
                        url: '/pages/home/park/park',
                    })
                }
            } else if (type == 7) {
                //登陆拦截
                if (!token) {
                    wx.showToast({
                        title: '您还没有登陆哦',
                        icon: 'none'
                    })

                    setTimeout(() => {
                        wx.navigateTo({
                            url: '/pages/login/login?back=/pages/home/home',
                        })
                    }, 1000)
                    return
                }
                //判断是否有企业
                // console.log('用户资料',app.globalData.userInfo)
                if (app.globalData.userInfo.companySign == 0) {
                    wx.navigateTo({
                        url: '/pages/park/company/edit/edit',
                    })
                } else {
                    wx.navigateTo({
                        url: '/pages/home/enterprise/enterprise',
                    })
                }
            } else if (type == 8) {
                //登陆拦截
                if (!token) {
                    wx.showToast({
                        title: '您还没有登陆哦',
                        icon: 'none'
                    })

                    setTimeout(() => {
                        wx.navigateTo({
                            url: '/pages/park/visiting-card/visiting-card',
                        })
                    }, 1000)
                    return
                } else {
                    wx.navigateTo({
                        url: '/pages/park/visiting-card/visiting-card',
                    })
                }
            }
        }
    },

    /**
     * 路由 - 更多分享
     */
    routeMoreShare: function () {
        wx.switchTab({
            url: '/pages/share/share',
        })
    },

    /**
     * 页面触底
     */
    onReachBottom: function () {
        this.data.formData.pageNum += 1
        this.data.formData.classify == 10 ? this.get_park_list() : this.data.formData.classify == 20 ? this.getCompanyList() : this.getAppletHomeHousing()
        // let that = this
        // let pageNum = this.data.parkQuery.pageNum
        // let pageNum2 = this.data.companyQuery.pageNum
        // if (this.data.reachBottomShow) {
        //     if (that.data.tagCurrent == 1) {
        //         pageNum++
        //         this.setData({
        //             ['parkQuery.pageNum']: pageNum
        //         })
        //         that.get_park_list()
        //     } else {
        //         pageNum2++
        //         this.setData({
        //             ['companyQuery.pageNum']: pageNum2
        //         })
        //         that.get_company_list()
        //     }
        //     // console.log('加载下一页', pageNum, pageNum2)
        // } else {
        //     // console.log('到底了',pageNum, pageNum)
        // }
    },

    /**
     * 路由 - 微信推广 - 园区房源定位
     */
    routeParkHouseSite: function (e) {
        //路由跳转
        let item = e.currentTarget.dataset.item
        // console.log(item)
        wx.navigateTo({
            url: '/pages/park/park?site=1&id=' + item.homeId
        })
    },
    housingResourceChange(event) {
        this.data.shareContent = event.detail
    },
    /**
     * 分享
     */
    onShareAppMessage: function () {
        let shareContent = this.data.shareContent
        // console.log(shareContent)
        return {
            title: '(' + shareContent.houseArea + '㎡' + shareContent.fitmentCase + ')' + shareContent.gardenName,
            imageUrl: shareContent.houseImg,
            path: '/pages/park/park?id=' + shareContent.gardenId + '&inviterUserId=' + app.globalData.userInfo.id
        }
    },
})